package org.itboys.product.web;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.itboys.admin.constant.AdminSessionConstant;
import org.itboys.commons.CommonConstants;
import org.itboys.commons.utils.ajax.AjaxUtils;
import org.itboys.commons.utils.servlet.ServletContextHolder;
import org.itboys.framework.query.JsonPageUtils;
import org.itboys.framework.spring.controller.BaseController;
import org.itboys.mongodb.utils.page.Page;
import org.itboys.mongodb.utils.query.QueryParamUtils;
import org.itboys.product.constant.ProductConstant;
import org.itboys.product.dto.ProductCategoryDto;
import org.itboys.product.dto.PromotionProductDTO;
import org.itboys.product.dto.PromotionUseProductDTO;
import org.itboys.product.entity.*;
import org.itboys.product.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

/**
 * 商品
 * @author weisky
 *
 */
@RestController
@RequestMapping("/product/product")
public class ProductController extends BaseController{

	@Autowired
	private ProductService productService;
	@Autowired
	private ProductCategoryService productCategoryService;
	@Autowired
	private ProductBrandService productBrandService;
	@Autowired
	private ProductTextService productTextService;
	@Autowired
	private ShopProductCategoryService shopProductCategoryService;
	@Autowired
	private ProductMinPriceService productMinPriceService;
	/**
	 * 跳到商品管理页面
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/toListVM")
	public ModelAndView toListVM(HttpServletRequest request, HttpServletResponse response,Model model) {
		return new ModelAndView("/ace/product/productList");
	}

    @RequestMapping("/toPromotionListVM")
    public ModelAndView toPromotionListVM(HttpServletRequest request, HttpServletResponse response,Model model) {
        return new ModelAndView("/ace/product/promotion-list");
    }

    @RequestMapping("/toCheckVM")
    public ModelAndView toCheckVM(HttpServletRequest request, HttpServletResponse response,Model model) {
        return new ModelAndView("ace/product/productCheckList");
    }

    @RequestMapping("/toServerVM")
    public ModelAndView toServerVM(HttpServletRequest request, HttpServletResponse response,Model model) {
        return new ModelAndView("ace/product/serverProductList");
    }

    @RequestMapping("/toPromotionGoodsVM")
    public ModelAndView toPromotionGoodsVM(HttpServletRequest request, HttpServletResponse response,Model model) {
        return new ModelAndView("ace/product/promotionGoodsList");
    }

    @RequestMapping("/toPromotionInputVM")
    public ModelAndView toPromotionInputVM(HttpServletRequest request, HttpServletResponse response,Model model) {
        return new ModelAndView("ace/product/promotionInput");
    }

	/**
	 * 获取商品列表 带分页参数
	 * @param request
	 * @param response
     */
	@RequestMapping("/list")
	public void list(HttpServletRequest request,HttpServletResponse response){
		Page<Product> page = productService.pageQuery(request);
		JsonPageUtils.renderJsonPage(page.getTotal(), page.getData(), response);
	}

    /**
     * 获取商品列表
     * @param request
     * @param response
     */
    @RequestMapping("/findAllProducts")
    public void findAllProducts(HttpServletRequest request,HttpServletResponse response){
        Map<String, Object> param = QueryParamUtils.builderQueryMap(request);
        List<Product> products = productService.list(param);
        List<PromotionUseProductDTO> needProducts = products.stream().map(p -> {
            PromotionUseProductDTO need = new PromotionUseProductDTO();
            need.setId(p.getId());
            need.setName(p.getName());
            return need;
        }).collect(Collectors.toList());
        AjaxUtils.renderJson(response, needProducts);
    }

	/**
	 * 跳转产品编辑界面
	 * @param id
	 * @param model
     * @return
     */
	@RequestMapping("/input")
	public ModelAndView input(@RequestParam(value = "id", required = false)Long id,
							  Model model){
		if(id != null && id > 0){
			ProductText text = productTextService.getByField("productId", id);
			model.addAttribute("productText", text);
			Product product = productService.getById(id);
			model.addAttribute("product", product);
		}
		return  new ModelAndView("ace/product/productInput");
	}

    /**
     * 跳转产品编辑界面
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("/serverProductInput")
    public ModelAndView serverProductInput(@RequestParam(value = "id", required = false)Long id,
                              Model model){
        if(id != null && id > 0){
            ProductText text = productTextService.getByField("productId", id);
            model.addAttribute("productText", text);
            Product product = productService.getById(id);
            model.addAttribute("product", product);
        }
        return  new ModelAndView("ace/product/serverProductInput");
    }
	
	@RequestMapping("/save")
	public void save(Product product,
					 @RequestParam(value="specDetails", required = false)List<Long> specDetails,
					 @RequestParam(value="productSpecDetails", required = false)String productSpecDetails,
			@RequestParam(required=false) String[] tagsArr,
			@RequestParam(value="imgFile", required = false) MultipartFile imgFile,
			@RequestParam(value="imgFiles", required = false) MultipartFile[] imgFiles,
			HttpServletRequest request,HttpServletResponse response){
        product.setStatus(ProductConstant.ProductStatus.PRODUCT_UNPUT);
        boolean result = productService.insert(product, imgFile, imgFiles, specDetails, productSpecDetails);
		//插入详情
		if(request.getParameter("textContent")!=null){
			ProductText productText = productTextService.getByField("productId", product.getId());
			if(productText == null){
				productText = new ProductText();
				productText.setProductId(product.getId());
				productText.setProductText(request.getParameter("textContent"));
				productTextService.insert(productText);
			}else{
				productText.setProductText(request.getParameter("textContent"));
				productTextService.update(productText);
			}
		}
		//插入售后服务
		/*if(request.getParameter("productAfterServer")!=null){
			ProductAfterServer productAfterServer=new ProductAfterServer();
			productAfterServer.setProductId(product.getId());
			productAfterServer.setProductAfterServer(request.getParameter("productAfterServer"));
			productAfterServerService.insert(productAfterServer);
		}*/
		if(result){
			AjaxUtils.renderText(response, CommonConstants.SUCCESS);
		}else{
			AjaxUtils.renderText(response, CommonConstants.FAIL);
		}
	}

	/**
	 * 查看商品基本信息
	 * @param productId
	 * @param request
	 * @param response
     */
	@RequestMapping("/getById")
	public void getById(Long productId,
			HttpServletRequest request,HttpServletResponse response){
		AjaxUtils.renderJson(response, productService.getById(productId));
	}

    /**
     * 查看商品分类
     */
    @RequestMapping("/getProductCategory")
    public void getProductCategory(Long productId,
                                   HttpServletResponse response) {
        List<ProductCategory> categories = productService.getProductCategory(productId);

        AjaxUtils.renderJson(response, categories.stream()
                .filter(p -> p != null).map(p -> {
            ProductCategoryDto dto = new ProductCategoryDto();
            dto.setId(p.getId());
            dto.setName(p.getName());
            return dto;
        }).collect(Collectors.toList()));
    }

	/**
	 * 查看商品详情
	 * @param productId
	 * @param request
	 * @param response
     */
	@RequestMapping("/getProductText")
	public void getProductText(Long productId,
						HttpServletRequest request,HttpServletResponse response){
		AjaxUtils.renderJson(response, productTextService.getByField("productId",productId));
	}

	/**
	 * 查看商品售后
	 * @param productId
	 * @param request
	 * @param response
     */
	@RequestMapping("/getProductAfter")
	public void getProductAfter(Long productId,
							   HttpServletRequest request,HttpServletResponse response){
		AjaxUtils.renderJson(response, productTextService.getByField("productId",productId));
	}

	/**
	 * 删除商品
	 * @param productId
	 * @param request
	 * @param response
     */
	@RequestMapping("/delete")
	public void delete(Long id,
			HttpServletRequest request,HttpServletResponse response){
		try {
            Product product = productService.getById(id);
            if (product == null) {
                AjaxUtils.renderText(response, CommonConstants.FAIL);
                return;
            }
			productService.delete(id);
            productMinPriceService.resetMinPrice(product.getSellerId());
			AjaxUtils.renderText(response, CommonConstants.SUCCESS);
		} catch (Exception e) {
			logger.error("/product/product/delete error", e);
			AjaxUtils.renderText(response, CommonConstants.FAIL);
		}
	}

    /**
     * 上架商品
     * @param productId
     * @param request
     * @param response
     */
    @RequestMapping("/shelve")
    public void shelve(Long id,
                     HttpServletRequest request,HttpServletResponse response){
        try {
            Product product = productService.getById(id);
            if (product == null || (product.getStatus() != ProductConstant.ProductStatus.PRODUCT_UNPUT  &&
                    product.getStatus() != ProductConstant.ProductStatus.PRODUCT_DOWN)) {
                AjaxUtils.renderText(response, CommonConstants.FAIL);
                return;
            }
            Object shopCenterId = ServletContextHolder.getSession().getAttribute(AdminSessionConstant.SHOP_CENTER_ID);
            if (shopCenterId != null) {
                productService.updateState(id, ProductConstant.ProductStatus.PRODUCT_PUT);
            } else {
                productService.updateState(id, ProductConstant.ProductStatus.PRODUCT_PASS);
            }
            AjaxUtils.renderText(response, CommonConstants.SUCCESS);
        } catch (Exception e) {
            logger.error("/product/product/shelve error", e);
            AjaxUtils.renderText(response, CommonConstants.FAIL);
        }
    }

    /**
     * 下架商品
     * @param productId
     * @param request
     * @param response
     */
    @RequestMapping("/unShelve")
    public void unShelve(Long id,
                       HttpServletRequest request,HttpServletResponse response){
        try {
            Product product = productService.getById(id);
            if (product == null || product.getStatus() != ProductConstant.ProductStatus.PRODUCT_PASS) {
                AjaxUtils.renderText(response, CommonConstants.FAIL);
                return;
            }
            productService.updateState(id, ProductConstant.ProductStatus.PRODUCT_DOWN);
            productMinPriceService.resetMinPrice(product.getSellerId());
            AjaxUtils.renderText(response, CommonConstants.SUCCESS);
        } catch (Exception e) {
            logger.error("/product/product/unShelve error", e);
            AjaxUtils.renderText(response, CommonConstants.FAIL);
        }
    }

    /**
     * 审核通过商品
     * @param productId
     * @param request
     * @param response
     */
    @RequestMapping("/pass")
    public void pass(Long id,
                       HttpServletRequest request,HttpServletResponse response){
        try {
            productService.updateState(id, ProductConstant.ProductStatus.PRODUCT_PASS);
            Product product = productService.getById(id);
            if (product != null) {
                productMinPriceService.updateMinPrice(product.getSellerId(), product.getPrice());
            }
            AjaxUtils.renderText(response, CommonConstants.SUCCESS);
        } catch (Exception e) {
            logger.error("/product/product/pass error", e);
            AjaxUtils.renderText(response, CommonConstants.FAIL);
        }
    }

    /**
     * 审核拒绝商品
     * @param productId
     * @param request
     * @param response
     */
    @RequestMapping("/refuse")
    public void refuse(Long id,
                     HttpServletRequest request,HttpServletResponse response){
        try {
            productService.updateState(id, ProductConstant.ProductStatus.PRODUCT_REJECT);
            AjaxUtils.renderText(response, CommonConstants.SUCCESS);
        } catch (Exception e) {
            logger.error("/product/product/pass refuse", e);
            AjaxUtils.renderText(response, CommonConstants.FAIL);
        }
    }

	/**
	 * 产品规格页面
	 * @param productId  产品id
	 * @param catId  分类id
	 * @param model
     * @return
     */
	@RequestMapping("/productSpec")
	public ModelAndView productSpec(@RequestParam("productId")Long productId,
									@RequestParam("catId")String catId,
									Model model){
		productService.getSpec(catId, productId, model);
		return new ModelAndView("ace/product/productSpecDetail");
	}

}
